package com.maoye.ossp.bpm.bpmsap.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.core.util.AppUtil;
import com.hotent.base.core.util.BeanUtils;
import com.hotent.base.core.util.string.StringUtil;
import com.hotent.bpmx.api.constant.BpmConstants;
import com.hotent.bpmx.api.exception.WorkFlowException;
import com.hotent.bpmx.api.helper.identity.BpmIdentityConverter;
import com.hotent.bpmx.api.model.identity.BpmIdentity;
import com.hotent.bpmx.api.model.process.inst.BpmProcessInstance;
import com.hotent.bpmx.api.model.process.nodedef.BpmNodeDef;
import com.hotent.bpmx.api.model.process.task.BpmTask;
import com.hotent.bpmx.api.plugin.core.context.BpmPluginContext;
import com.hotent.bpmx.api.service.BpmDefinitionService;
import com.hotent.bpmx.api.service.BpmInstService;
import com.hotent.bpmx.api.service.BpmTaskActionService;
import com.hotent.bpmx.api.service.BpmTaskService;
import com.hotent.bpmx.core.engine.inst.DefaultProcessInstCmd;
import com.hotent.bpmx.core.engine.task.cmd.DefaultTaskFinishCmd;
import com.hotent.bpmx.core.model.identity.DefaultBpmIdentity;
import com.hotent.bpmx.natapi.inst.NatProInstanceService;
import com.hotent.bpmx.persistence.model.DefaultBpmProcessInstance;
import com.hotent.bpmx.plugin.task.nodepermissions.context.NodePermissionsPluginContext;
import com.hotent.bpmx.plugin.task.nodepermissions.def.NodePermissionsPluginDef;
import com.hotent.org.api.model.Group;
import com.hotent.org.api.model.User;
import com.hotent.sys.util.RequestUtil;
import com.maoye.org.core.groupgeneral.impl.MoiPostService;
import com.maoye.org.core.service.MoiUserService;
import com.maoye.ossp.bpm.workflow.service.IBpmWorkFlowService;
import com.maoye.ossp.bpm.workflow.service.IProcessService;
import com.maoye.ossp.bpmagent.context.BpmAgentConfiguration;
import com.maoye.ossp.bpmagent.engine.IFormValidationService;
import com.maoye.ossp.bpmagent.model.ProcessInstance;
import com.maoye.ossp.bpmagent.model.TaskOpinion;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.util.RequestContext;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sap.ISapDataInteractionService;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.local.PostService;

/**
 * SAP 任务流程查询Controller
 * 
 * @author cheng
 * @date 2014-04-22
 * @version 1.0
 * 
 */
@Controller
@RequestMapping("bpm/bpmsap/")
public class BpmSapController extends BaseController {

	@Resource(name = "bpmAgentConfiguration")
	private BpmAgentConfiguration bpmAgentConfiguration;
	@Resource
	protected ISapDataInteractionService sapDataInteractionService;
	@Resource
	protected IFormValidationService formValidationService;
	@Resource
	protected PostService postService;
	@Resource
	protected MoiPostService moiPostService;
	/**
	 * 流程实例服务
	 */
	@Resource
	private BpmInstService bpmInstService;

	/**
	 * 流程定义服务
	 */
	@Resource
	private BpmDefinitionService bpmDefinitionService;

	/**
	 * 流程任务服务
	 */
	@Resource
	private BpmTaskService bpmTaskService;

	@Resource
	private MoiUserService moiUserService;

	@Resource
	private IBpmWorkFlowService bpmWorkFlowService;

	@Resource
	private BpmTaskActionService bpmTaskActionService;

	@Resource
	private IProcessService processService;

	/**
	 * 流程实例服务（直接对接activity）
	 */
	@Resource
	private NatProInstanceService natProInstanceService;

	/**
	 * 打开流程流程申请界面
	 * 
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "add")
	public String add(HttpServletRequest request, Model model) throws Exception {
		String flowKey = request.getParameter("flowKey");// 流程定义的key
		// 获取流程启动信息
		Map<String, Object> workFlow = bpmWorkFlowService.getSAPWorkFlow(
				IBpmWorkFlowService.SAP_START, new RequestContext(request));
		String userId = UserUtils.getCurrentUserIdStr();
		String proInsId = (String) workFlow.get("proInsId");// 设置流程实例ID

		// 获取SAP表单URL
		ProcessInstance agentProInstance = new ProcessInstance();
		agentProInstance.setFormKey(flowKey);
		agentProInstance.setInstanceId(proInsId);
		Map<String, Object> sapDataMap = sapDataInteractionService
				.getGetBusinessData(agentProInstance, userId);
		if (sapDataMap != null) {
			model.addAttribute("sapUrl", sapDataMap.get("sapUrl"));// 设置SAP表单URL
		}
		model.addAttribute("proInsId", proInsId);
		model.addAttribute("isVal", "1");
		model.addAttribute("flowKey", flowKey);
		model.addAttribute("flowStatus", BpmProcessInstance.STATUS_DRAFT);
		model.addAttribute("workflow", workFlow);
		model.addAttribute("subject", workFlow.get("subject"));
		model.addAttribute("workflowdata", JSONObject.fromObject(workFlow));
		return "/bpm/bpmsap/process/startIndex";
	}

	/**
	 * 启动业务界面跳转
	 * 
	 * @author zhuangwl
	 * @date 2014-8-21
	 * 
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @param baseInfo
	 *            启动JSON
	 * 
	 * @return
	 */
	@RequestMapping(value = "save")
	public String save(HttpServletRequest request, Model model) {
		// 启动流程并更新sap表单状态
		processService.startProcess(request);
		return SUCCESS;
	}

	/**
	 * 获取流程审批历史记录 获取当前流程信息
	 * 
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "taskExecute/{taskId}")
	public String taskExecute(@PathVariable(value = "taskId") String taskId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String taskInfo = bpmAgentConfiguration.getBpmAgentContext()
				.getTaskEngine("taskEngineImpl").getTaskById(taskId);
		JSONObject taskInfoJson = JSONObject.fromObject(taskInfo);
		// 获取流程审批记录
		List<TaskOpinion> list = new ArrayList<TaskOpinion>();
		// 获取历史审批记录
		list = bpmAgentConfiguration
				.getBpmAgentContext()
				.getProcessInstanceEngine("processInstanceEngineImpl")
				.getTaskOpinionByProInsId(taskInfoJson.getString("instanceId"),
						String.valueOf(UserUtils.getUser().getId()));

		model.addAttribute("taskInstance", taskInfo);
		model.addAttribute("bpmnDefId", taskInfoJson.getString("bpmnDefId"));
		model.addAttribute("instanceId", taskInfoJson.getString("instanceId"));
		// 获取操作
		if (taskInfoJson.containsKey("optBtnKeys")
				&& StringUtil.isNotEmpty(taskInfoJson.getString("optBtnKeys"))) {
			Map<String, String> optBtnMap = new HashMap<String, String>();
			String optBtnKeys = taskInfoJson.getString("optBtnKeys");
			String[] optBtns = optBtnKeys.split(";");
			for (String optBtn : optBtns) {
				optBtnMap.put(optBtn.split("-")[0], optBtn.split("-")[1]);
			}
			model.addAttribute("optBtnMap", optBtnMap);
		}
		// 流程图配置
		// BpmDefLayout layout = bpmAgentConfiguration
		// .getBpmAgentContext()
		// .getProcessInstanceEngine("processInstanceEngineImpl")
		// .getDiagramDiv(taskInfoJson.getString("proDefId"),
		// taskInfoJson.getString("bpmnDefId"));
		// model.addAttribute("bpmDefLayout", layout);

		model.addAttribute("taskId", taskInfoJson.getString("taskId"));
		model.addAttribute("list", list);
		model.addAttribute("userName", UserUtils.getCurrentUserName());
		// 获取sap URL
		String sapUrl = bpmAgentConfiguration.getBpmAgentContext()
				.getTaskEngine("taskEngineImpl")
				.getSapUrl(taskInfoJson.getString("taskId"), "sapUrl");
		model.addAttribute("sapUrl", sapUrl);
		return "/bpm/bpmsap/task/taskExecute";
	}

	/**
	 * 执行任务
	 * 
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @param baseInfo
	 *            启动JSON
	 * @return
	 */
	@RequestMapping(value = "execute")
	public String execute(RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String messageInfo = null;
		String taskId = request.getParameter("taskId");
		if (StringUtil.isEmpty(taskId)) {
			throw new WorkFlowException("传入的任务ID（taskId）的值为空，执行流程动作失败！"); // 抛出异常
		}

		String actionName = RequestUtil.getString(request, "actionName",
				"agree");
		String opinion = RequestUtil.getString(request, "opinionIdea", "");
		String nodeId = RequestUtil.getString(request, "nodeId", "");
		String executors = RequestUtil.getString(request, "executors");
		String editNodeIds = RequestUtil.getString(request, "editNodeIds");
		String userIds = RequestUtil.getString(request, "userIds");

		String formIdentity = RequestUtil.getString(request,
				BpmConstants.BPM_FORM_IDENTITY);

		DefaultTaskFinishCmd cmd = new DefaultTaskFinishCmd();
		cmd.setTaskId(taskId);
		cmd.setActionName(actionName);
		cmd.setApprovalOpinion(opinion);

		// 设置可编辑节点的执行用户
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, List<BpmIdentity>> specUserMap = getBpmIdentity(
				editNodeIds, userIds);
		if (BeanUtils.isNotEmpty(specUserMap)) {
			BpmTask task = bpmTaskService.getByTaskId(taskId);
			Object originalUserObj = natProInstanceService.getVariables(
					task.getBpmnInstId()).get(BpmConstants.BPM_NODE_USERS);
			if (BeanUtils.isNotEmpty(originalUserObj)) {
				Map<String, List<BpmIdentity>> originalUserMap = (Map<String, List<BpmIdentity>>) originalUserObj;
				for (String key : originalUserMap.keySet()) {
					if (specUserMap.containsKey(key)) {

					} else {
						specUserMap.put(key, originalUserMap.get(key));
					}
				}
			}
			params.put(BpmConstants.BPM_NODE_USERS, specUserMap);
			cmd.setVariables(params);
		}
		// 设置流程实例的下一分支
		if (StringUtil.isNotEmpty(nodeId) && "agree".equals(actionName)) {
			cmd.setDestination(nodeId);
		}
		// TODO 设置目标节点映射
		// Map<String,List<BpmIdentity>>
		// nodeIdentityMap=getBpmIdentity(executors);
		// cmd.setBpmIdentities(nodeIdentityMap);
		// 执行任务
		// 设置线程用户
		User user = moiUserService.getById(UserUtils.getCurrentUserIdStr());
		com.hotent.bpmx.api.context.ContextUtil.setCurrentUser(user);
		bpmTaskActionService.finishTask(cmd);
		// // 获取备选列表
		// String nodeOptUsers = request.getParameter("nodeOptUsers");
		// // 设置备选列表
		// if (!StringUtil.isEmpty(nodeOptUsers)) {
		// JSONObject nodeOptUsersJson =
		// JSONObject.fromObject(nodeOptUsers);
		// Map<String, String> optUserMap = (Map<String, String>)
		// nodeOptUsersJson.toBean(nodeOptUsersJson,
		// Map.class);
		// varInfo.putAll(nodeOptUsersJson);
		// }
		model.addAttribute("messageTitle", "任务执行成功");
		return SUCCESS;
	}

	/**
	 * 启动业务界面跳转
	 * 
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @param baseInfo
	 *            启动JSON
	 * @return
	 */
	@RequestMapping(value = "startSapProcess")
	public String startProcess(RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			String flowKey = request.getParameter("flowKey");
			// 获取流程启动信息
			Map<String, Object> workFlow = bpmWorkFlowService.getSAPWorkFlow(
					IBpmWorkFlowService.SAP_START, new RequestContext(request));
			// 如果流程信息不为空
			if (workFlow != null && !workFlow.isEmpty()) {
				// 启动草稿流程
				DefaultProcessInstCmd processInstCmd = new DefaultProcessInstCmd();
				processInstCmd.setFlowKey(flowKey);
				String userId = UserUtils.getCurrentUserIdStr();
				if (StringUtils.isEmpty(userId)) {
					model.addAttribute("messageTitle", "任务执行失败！");
					model.addAttribute("messageInfo",
							"“" + UserUtils.getCurrentUserName() + "”该用户不存在！");
					return "/bpm/bpmsap/error";
				}
				// 设置线程用户
				User user = moiUserService.getById(userId);
				com.hotent.bpmx.api.context.ContextUtil.setCurrentUser(user);
				BpmProcessInstance instance = bpmInstService
						.saveDraft(processInstCmd);
				// 设置流程实例
				model.addAttribute("proInsId", instance.getId());
				// TODO 获取SAP动态URL
				// 封装参数
				ProcessInstance agentProInstance = new ProcessInstance();
				agentProInstance.setFormKey(flowKey);
				agentProInstance.setInstanceId(instance.getId());
				Map<String, Object> sapDataMap = sapDataInteractionService
						.getGetBusinessData(agentProInstance, userId);
				if (sapDataMap != null) {
					model.addAttribute("sapUrl", sapDataMap.get("sapUrl"));
				}
				model.addAttribute("isVal", "1");
				model.addAttribute("flowKey", flowKey);
				model.addAttribute("flowStatus", instance.getStatus());
				model.addAttribute("workflow", workFlow);
				model.addAttribute("title", instance.getProcDefName());
				model.addAttribute("workflowdata",
						JSONObject.fromObject(workFlow));
			}
		} catch (Exception e) {
			e.printStackTrace();
			// String messageInfo = e.getMessage();
			// model.addAttribute("messageTitle", "任务执行失败!");
			// model.addAttribute("messageInfo", messageInfo);
			// return "/bpm/bpmsap/error";
		}
		return "/bpm/bpmsap/process/startIndex";
	}

	/**
	 * 启动业务界面跳转
	 * 
	 * @param redirectAttributes
	 * @param request
	 * @param response
	 * @param model
	 * @param baseInfo
	 *            启动JSON
	 * @return
	 */
	@RequestMapping(value = "executeSapProcess")
	public String executeSapProcess(RedirectAttributes redirectAttributes,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		try {
			DefaultBpmProcessInstance proIns = new DefaultBpmProcessInstance();
			proIns.setId(request.getParameter("proInsId"));
			proIns.setStatus(request.getParameter("flowStatus"));
			String editNodeIds = RequestUtil.getString(request, "editNodeIds");
			String userIds = RequestUtil.getString(request, "userIds");
			Map<String, Object> varMap = new HashMap<String, Object>();
			// 设置线程用户
			User user = moiUserService.getById(UserUtils.getCurrentUserIdStr());
			com.hotent.bpmx.api.context.ContextUtil.setCurrentUser(user);
			// TODO判断是否有问题
			varMap.put("sapUrl", request.getParameter("sapUrl"));
			// 设置可编辑节点的执行用户
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, List<BpmIdentity>> specUserMap = getBpmIdentity(
					editNodeIds, userIds);
			if (BeanUtils.isNotEmpty(specUserMap)) {
				varMap.put(BpmConstants.BPM_NODE_USERS, specUserMap);
			}
			BpmProcessInstance bpmProcessInstance = bpmInstService
					.startDraftProcessInstance(proIns, varMap);
		} catch (Exception e) {
			e.printStackTrace();
			// String messageInfo = e.getMessage();
			// model.addAttribute("messageTitle", "任务执行失败");
			// model.addAttribute("messageInfo", messageInfo);
			// return "/bpm/bpmsap/error";
		}
		model.addAttribute("messageTitle", "任务执行成功");
		return SUCCESS;
	}

	// TODO DELETE
	@RequestMapping(value = "processDefinition")
	public String processDefinition(HttpServletRequest request, Model model) {
		return "/bpm/bpmsap/def/processDefinition";
	}

	@RequestMapping(value = "valitionForm")
	public void valitionForm(HttpServletRequest request,
			HttpServletResponse response) {
		// String data = request.getParameter("data");
		// TODO 参数不能够为空 异常处理
		PrintWriter out = null;
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			// 这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
			response.setCharacterEncoding("UTF-8");
			// JSONObject dataJson = JSONObject.fromObject(data);
			String property = request.getParameter("sysType");
			String insId = request.getParameter("proInsId");
			String flowKey = request.getParameter("flowKey");
			String valType = request.getParameter("valType");
			// 校验数据
			Map<String, Object> result = formValidationService
					.checkFormByWebservice(property, insId, flowKey,
							UserUtils.getCurrentUserIdStr(), valType);
			String messageType = (String) result.get("messagetype");
			String message = (String) result.get("message");
			// 封装校验返回值
			JSONObject messageJson = new JSONObject();
			messageJson.element("messagetype", messageType);
			messageJson.element("message", message);

			out = response.getWriter();
			out.print(messageJson.toString());
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			out.flush();
			out.close();
		}
	}

	/**
	 * 审批的任务信息 通过流程状态的不同查询不同任务信息
	 * 
	 * @param status
	 *            任务状态
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	// @RequestMapping("approvedTask/{status}")
	// public String approvedTask(@PathVariable(value = "status") String status,
	// HttpServletRequest request, HttpServletResponse response,
	// Model model) {
	// // TODO 缺失用户ID（通过会话session获取用户ID）
	// User user = UserUtils.getUser();
	// Long userId = user.getId();
	// List<TaskInstance> list = new ArrayList<TaskInstance>();
	// list = bpmAgentConfiguration.getBpmAgentContext()
	// .getTaskEngine("taskEngineImpl")
	// .getTaskByUserIdandStatus(userId.toString(), status);
	//
	// model.addAttribute("list", list);
	//
	// return resultPage("/bpm/bpmsap/task/approvedTask", model, request);
	// }

	/**
	 * 审批流程信息 通过流程状态查询不同流程信息
	 * 
	 * @param status
	 *            流程状态
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	// TODO DELETE
	@RequestMapping("approvedProcessList/{status}")
	public String approvedProcess(
			@PathVariable(value = "status") String status,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		// 初始化Page信息
		Page page = initPage(request);
		// TODO 缺失用户ID（通过会话session获取用户ID）
		Long userId = UserUtils.getUser().getId();
		List<ProcessInstance> list = null;
		if ("1".equals(status)) {
			list = bpmAgentConfiguration
					.getBpmAgentContext()
					.getProcessInstanceEngine("processInstanceEngineImpl")
					.getProInsListByTaskUserId(String.valueOf(userId),
							page.getPageNo(), page.getPageSize());
		}
		if ("2".equals(status)) {
			list = bpmAgentConfiguration
					.getBpmAgentContext()
					.getProcessInstanceEngine("processInstanceEngineImpl")
					.getAttendProInsListByTaskUserId(String.valueOf(userId),
							page.getPageNo(), page.getPageSize());
		}
		if ("3".equals(status)) {
			list = bpmAgentConfiguration
					.getBpmAgentContext()
					.getProcessInstanceEngine("processInstanceEngineImpl")
					.getProcessInstancesByUserId(String.valueOf(userId),
							page.getPageNo(), page.getPageSize());
		}
		page.setList(list);
		model.addAttribute("page", page);
		return resultPage("/bpm/bpmsap/process/approvedProcessList", model,
				request);
	}

	/**
	 * 通过任务Id 查询任务信息
	 * 
	 * @param taskId
	 *            任务ID
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	// @RequestMapping("taskView/{taskId}")
	// public String taskView(@PathVariable(value = "taskId") String taskId,
	// HttpServletRequest request, HttpServletResponse response,
	// Model model) {
	// TaskInstance taskInstance = new TaskInstance();
	// taskInstance = bpmAgentConfiguration.getBpmAgentContext()
	// .getTaskEngine("taskEngineImpl")
	// // .getTaskById(taskId);
	// .getTaskByProcessInstanceId(taskId);
	// model.addAttribute("taskInstance", taskInstance);
	// return "/bpm/bpmsap/task/taskView";
	// }

	/**
	 * 通过实例ID，查询流程实例信息
	 * 
	 * @param instanceId
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("processView/{instanceId}")
	public String processView(
			@PathVariable(value = "instanceId") String instanceId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		RequestContext context = new RequestContext(request);
		context.setAttribute("proInsId", instanceId);
		Map<String, Object> workflow = bpmWorkFlowService.getSAPWorkFlow(
				IBpmWorkFlowService.SAP_APPROVE, context);
		// 获取SAP - Url
		String sapUrl = (String) workflow.get("sapUrl");
		// 替换用户参数 P_PERNR=用户ID
		sapUrl = getSapUrl(sapUrl);
		model.addAttribute("sapUrl", sapUrl);
		workflow.remove("sapUrl");
		model.addAttribute("workflow", workflow);
		model.addAttribute("title", workflow.get("subject"));
		model.addAttribute("workflowdata", JSONObject.fromObject(workflow));
		return "/bpm/bpmsap/task/taskExecute";
	}

	@RequestMapping(value = "error")
	public String error(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		model.addAttribute("messageInfo", request.getAttribute("messageInfo"));
		return "/bpm/bpmsap/error";
	}

	@RequestMapping(value = "success")
	public String success(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "/bpm/bpmsap/success";
	}

	@RequestMapping(value = "delete/{proInsId}")
	public String delete(@PathVariable("proInsId") String proInsId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String messageInfo = null;
		try {
			String result = bpmAgentConfiguration
					.getBpmAgentContext()
					.getProcessInstanceEngine("processInstanceEngineImpl")
					.removeProcessInstance(proInsId,
							UserUtils.getCurrentUserIdStr());
			JSONObject resultJson = JSONObject.fromObject(result);
			if ("1002".equals(resultJson.getString("code"))) {
				throw new Exception(resultJson.getString("msg"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			// messageInfo = e.getMessage();
			// model.addAttribute("messageTitle", "流程删除失败");
			// model.addAttribute("messageInfo", messageInfo);
			// return "/bpm/bpmsap/error";
		}
		model.addAttribute("messageTitle", "流程删除成功");
		return SUCCESS;
	}

	@RequestMapping(value = "admin/{proInsId}")
	public String admin(@PathVariable("proInsId") String proInsId,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		String messageInfo = null;
		try {
			// 获取当前流程任务列表
			// String tasks =
			// bpmAgentConfiguration.getBpmAgentContext().getTaskEngine("taskEngineImpl")
			// .getTasksInstId(proInsId);
			List<BpmTask> tasks = bpmTaskService.getTasksInstId(proInsId);
			JSONArray jsonArray = new JSONArray();
			JSONObject workFlowInfoJson = new JSONObject();
			StringBuffer outcomeNodeNames = new StringBuffer();
			StringBuffer outcomeNodeIds = new StringBuffer();
			for (BpmTask task : tasks) {
				JSONObject resultJson = new JSONObject();
				resultJson.element("taskId", task.getTaskId());
				resultJson.element("taskName", task.getName());
				jsonArray.add(resultJson);

				// 获取当前任务节点定义
				BpmNodeDef nodeDef = bpmDefinitionService
						.getBpmNodeDefByDefIdNodeId(task.getProcDefId(),
								task.getNodeId());
				// 获取下一节点
				List<BpmNodeDef> outcomeNodes = nodeDef.getOutcomeNodes();
				for (BpmNodeDef bpmNodeDef : outcomeNodes) {
					if (StringUtil.isNotEmpty(outcomeNodeIds.toString())) {
						outcomeNodeIds.append(";");
					}
					outcomeNodeIds.append(bpmNodeDef.getNodeId());
					if (StringUtil.isNotEmpty(outcomeNodeNames.toString())) {
						outcomeNodeNames.append(";");
					}
					outcomeNodeNames.append(bpmNodeDef.getName());
				}
			}
			workFlowInfoJson.element("outcomeNodeIds",
					outcomeNodeIds.toString());
			workFlowInfoJson.element("outcomeNodes",
					outcomeNodeNames.toString());

			model.addAttribute("workFlowInfo", workFlowInfoJson.toString());
			model.addAttribute("tasks", jsonArray.toString());
			model.addAttribute("proInsId", proInsId);
			// if ("1002".equals(resultJson.getString("code"))) {
			// throw new Exception(resultJson.getString("msg"));
			// }
		} catch (Exception e) {
			messageInfo = e.getMessage();
			model.addAttribute("messageTitle", "操作失败");
			model.addAttribute("messageInfo", messageInfo);
			return "/bpm/bpmsap/error";
		}
		return "/bpm/bpmsap/process/flowAdminOpt";
	}

	@RequestMapping(value = "adminopt")
	public String adminOpt(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String messageInfo = null;
		try {
			// 获取特权人操作信息
			String optInfo = request.getParameter("optInfo");
			// 判断特权人操作类型 editTaskExecutor:修改处理人 finishTask:完成当前任务
			// TODO 后期抽取方法
			JSONObject optInfoJson = JSONObject.fromObject(optInfo);
			String optType = optInfoJson.getString("type");
			JSONObject dataJson = optInfoJson.getJSONObject("data");
			if ("editTaskExecutor".equals(optType)) {
				String assigner = dataJson.getString("user").replace("|", ":");
				String assignerId = assigner.split(":")[0];
				if (StringUtil.isNotEmpty(assignerId)) {
					bpmTaskService.assigTask(dataJson.getString("task"),
							assignerId);
				}
				// bpmAgentConfiguration
				// .getBpmAgentContext()
				// .getTaskEngine("taskEngineImpl")
				// .assigTask(dataJson.getString("task"), assignerId,
				// String.valueOf(UserUtils.getCurrentUserId()));
			}
			if ("finishTask".equals(optType)) {
				// JSONObject baseInfo = new JSONObject();
				// baseInfo.element("taskId", dataJson.getString("task"));
				// baseInfo.element("actionName", "agree");
				// baseInfo.element("approvalOpinion", "特权人直接通过");
				// 设置线程用户
				User user = moiUserService.getById(UserUtils
						.getCurrentUserIdStr());
				com.hotent.bpmx.api.context.ContextUtil.setCurrentUser(user);
				DefaultTaskFinishCmd finishCmd = new DefaultTaskFinishCmd();
				finishCmd.setActionName("agree");
				finishCmd.setApprovalOpinion("特权人直接通过");
				finishCmd.setTaskId(dataJson.getString("task"));
				if (dataJson.containsKey("nodeId")
						&& StringUtil.isNotEmpty(dataJson.getString("nodeId"))) {
					finishCmd.setDestination(dataJson.getString("nodeId"));
				}
				bpmTaskActionService.finishTask(finishCmd);
				// bpmAgentConfiguration.getBpmAgentContext().getTaskEngine("taskEngineImpl")
				// .executeTask(baseInfo.toString(), null,
				// String.valueOf(UserUtils.getCurrentUserId()));
			}

		} catch (Exception e) {
			messageInfo = e.getMessage();
			model.addAttribute("messageTitle", "操作失败");
			model.addAttribute("messageInfo", messageInfo);
			return "/bpm/bpmsap/error";
		}
		model.addAttribute("messageTitle", "操作成功");
		return "/bpm/bpmsap/optSuccess";
	}

	@RequestMapping(value = "editNodeAdmin/{proInsId}/{nodeId}")
	public String editNodeAdmin(@PathVariable("proInsId") String proInsId,
			@PathVariable("nodeId") String nodeId, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String messageInfo = null;
		try {
			BpmNodeDef nodeDef = bpmDefinitionService
					.getBpmNodeDefByDefIdNodeId(proInsId, nodeId);
			List<BpmPluginContext> bpmPluginContexts = nodeDef
					.getBpmPluginContexts();
			// 节点定义参数
			JSONObject editNodeInfo = new JSONObject();
			// 循环插件
			for (BpmPluginContext bpmPluginContext : bpmPluginContexts) {
				// 节点权限
				if (bpmPluginContext instanceof NodePermissionsPluginContext) {
					NodePermissionsPluginContext nodePermissionsPluginContext = (NodePermissionsPluginContext) bpmPluginContext;
					NodePermissionsPluginDef def = (NodePermissionsPluginDef) nodePermissionsPluginContext
							.getBpmPluginDef();
					if (def.getEditNodes() != null) {
						editNodeInfo.element("editNodeNames", def
								.getEditNodes().getNodeNames());
						editNodeInfo.element("editNodeIds", def.getEditNodes()
								.getNodeIds());
					}
				}
			}
			model.addAttribute("defId", proInsId);
			model.addAttribute("editNodeInfo", editNodeInfo.toString());
		} catch (Exception e) {
			messageInfo = e.getMessage();
			e.printStackTrace();
			model.addAttribute("messageTitle", "操作失败");
			model.addAttribute("messageInfo", messageInfo);
			return "/bpm/bpmsap/error";
		}
		return "/bpm/bpmsap/process/userOpt";
	}

	// TODO DELETE
	private Page initPage(HttpServletRequest request) {
		Page page = new Page();
		// 目前固定15行
		page.setPageSize(10);
		String pageNo = (String) request.getParameter("pageNo");
		if (StringUtil.isNotEmpty(pageNo)) {
			// 设置分页
			page.setPageNo(Integer.valueOf(pageNo));
		}
		return page;
	}

	// 根据页面传过来的可编辑节点ID，用户ID 得到封装好的用户集合
	private Map<String, List<BpmIdentity>> getBpmIdentity(String editNodeIds,
			String userIdS) {
		Map<String, List<BpmIdentity>> map = new HashMap<String, List<BpmIdentity>>();
		if (StringUtil.isEmpty(editNodeIds) || StringUtil.isEmpty(userIdS))
			return map;
		String[] editNodeArray = editNodeIds.split("#");
		String[] userIdArray = userIdS.split("#");
		BpmIdentityConverter bpmIdentityConverter = AppUtil
				.getBean(BpmIdentityConverter.class);
		for (int i = 0; i < editNodeArray.length; i++) {
			List<BpmIdentity> userList = new ArrayList<BpmIdentity>();
			DefaultBpmIdentity bpmIdentity = null;
			String[] userIds = userIdArray[i].split(";");
			for (String userIdInfo : userIds) {
				if (userIdInfo.endsWith("user")) {
					User user = moiUserService
							.getById(userIdInfo.split("\\|")[0]);
					bpmIdentity = (DefaultBpmIdentity) bpmIdentityConverter
							.convertUser(user);
					bpmIdentity.setGroupType("user");
				} else {
					Group group = moiPostService.getByGroupKey(userIdInfo
							.split("\\|")[0]);
					bpmIdentity = (DefaultBpmIdentity) bpmIdentityConverter
							.convertGroup(group);
					// 设置关联关系
					bpmIdentity.setRelType("post");
					bpmIdentity.setGroupType("post");
				}
				userList.add(bpmIdentity);
			}
			map.put(editNodeArray[i], userList);
		}
		return map;
	}

	private String getSapUrl(String sapUrl) {
		// 获取用户ID
		String userId = UserUtils.getCurrentUserIdStr();
		// 构建新的用户参数
		String userparam = "P_PERNR=" + userId;
		sapUrl = sapUrl.replace("P_PERNR=00000000", userparam);
		return sapUrl;
	}
}
